package com.easemob.helpdesk.fragment;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.easemob.helpdesk.activity.MainActivity;
import com.easemob.helpdesk.entity.TabEntity;
import com.easemob.helpdesk.utils.CommonUtils;
import com.easemob.helpdesk.utils.TimeInfo;
import com.easemob.helpdesk.widget.AddrSearchView;
import com.easemob.helpdesk.widget.CustomListView;
import com.easemob.helpdesk.widget.CustomViewPager;
import com.easemob.helpdesk.widget.NoScrollGridView;
import com.easemob.helpdesk.widget.TimeSelectView;
import com.easemob.helpdesk.widget.WarpLinearLayout;
import com.easemob.helpdesk.widget.pickerview.SimplePickerView;
import com.easemob.helpdesk.widget.popupwindow.VillageFilterWindow;
import com.flyco.roundview.RoundTextView;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.housekeeperapp.BuildConfig;
import com.housekeeperapp.MainApplication;
import com.housekeeperapp.R;
import com.hyphenate.kefusdk.HDConnectionListener;
import com.hyphenate.kefusdk.chat.HDClient;
import com.hyphenate.kefusdk.manager.main.NoticeManager;
import com.hyphenate.kefusdk.manager.session.HistorySessionManager;
import com.hyphenate.kefusdk.utils.HDLog;
import com.hyphenate.util.NetUtils;

import org.w3c.dom.Text;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class OwnerTabMsgFragment extends Fragment implements AddrSearchView.searchListener {

    private static final String TAG = MsgFragment.class.getSimpleName();
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    private ArrayList<Fragment> fragments;

    private String[] mTabTitles = {"当前会话", "消息记录"};
    private CurrentSessionFragment currentSessionFragment;
//    private WaitAccessFragment mWaitAccessFragment;
    private OwnerMsgFragment ownerMsgFragment;
    private  void initFindView(View view){
        mViewPager=view.findViewById(R.id.msg_viewpager);

        mTabLayout=view.findViewById(R.id.tablayout);
        ll_right=view.findViewById(R.id.ll_right);
        filterText=view.findViewById(R.id.ib_add_task);
        searchIcon=view.findViewById(R.id.ib_menu_more);

        errorItem=view.findViewById(R.id.rl_error_item);

    }
    protected CustomViewPager mViewPager;

    protected CommonTabLayout mTabLayout;

    protected LinearLayout ll_right;

    public TextView filterText;
    public ImageView searchIcon;
    public RelativeLayout errorItem;
    public TextView errorText;

    private AddrSearchView addrSearchView;

    private HDConnectionListener connectionListener;




    public OwnerTabMsgFragment() {
        // Required empty public constructor

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_msg, container, false);
        initFindView(view);
        return view;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        String userType = "";
        if (getResources().getString(R.string.HU_LI_ZHAN).equals(MainActivity.productKey)){
            userType = "用户";
        }else{
            userType = "业主";
        }
        mTabTitles[1] = userType +mTabTitles[1];
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        mViewPager.setOffscreenPageLimit(1);

        fragments = getFragments();

        errorText = (TextView) errorItem.findViewById(R.id.tv_connect_errormsg);

        for (int i = 0; i < mTabTitles.length; i++){
            mTabEntities.add(new TabEntity(mTabTitles[i]));
        }

        mViewPager.setAdapter(new MyPagerAdapter(getActivity().getSupportFragmentManager()));

        if (getResources().getString(R.string.LI_XIAO_SHUANG).equals(MainActivity.productKey)){
            ll_right.setVisibility(View.GONE);
        }else{
            ll_right.setVisibility(View.VISIBLE);
        }

        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
//                .selectTab(position);
                if (!getResources().getString(R.string.LI_XIAO_SHUANG).equals(MainActivity.productKey)){
                    if(position == 0){
                        ll_right.setVisibility(View.VISIBLE);
                    }else{
                        ll_right.setVisibility(View.GONE);
                    }
                }else{
                    ll_right.setVisibility(View.GONE);
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        mTabLayout.setTabData(mTabEntities);
        mTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                mViewPager.setCurrentItem(position);
//                if(position == 2){// 历史会话
//                    historySessionFragment.onFreshData();
//                }

                if(position != 0){
                    if(addrSearchView != null){
                        addrSearchView.reset();
                    }
                }

            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        if (!getResources().getString(R.string.LI_XIAO_SHUANG).equals(MainActivity.productKey)) {
            ll_right.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //showSearchView();
                    if (mTabLayout.getCurrentTab() == 0) {//当前会话
                        if (addrSearchView == null) {
                            addrSearchView = new AddrSearchView(getActivity(), OwnerTabMsgFragment.this, false);
                            addrSearchView.showSearchView();
                            if (currentSessionFragment != null) {
                                currentSessionFragment.hideSoftKeyboard();
                            }

                        } else {
                            if (addrSearchView.isShowing()) {
                                addrSearchView.hideSearchView();
                            } else {
                                addrSearchView.showView();
                                if (currentSessionFragment != null) {
                                    currentSessionFragment.hideSoftKeyboard();
                                }
                            }

                        }
                    }
                }
            });
        }

        connectionListener = new HDConnectionListener() {
            @Override
            public void onConnected() {
                HDLog.e(TAG, "onConnected");
                if (getActivity() == null){
                    return;
                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (errorItem != null)
                            errorItem.setVisibility(View.GONE);
                        HDLog.e(TAG, "onConnected--error--GONE");
                    }
                });
            }

            @Override
            public void onAuthenticationFailed(int errorCode) {
                if (getActivity() == null){
                    return;
                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // Jump to the login UI
                        MainApplication.getInstance().getEventEmitter().sendEvent("logout");

                    }
                });

            }

            @Override
            public void onDisconnected() {
                HDLog.d(TAG, "onDisconnected");
                if (getActivity() == null){
                    return;
                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (errorItem != null)
                            errorItem.setVisibility(View.VISIBLE);
                        if(NetUtils.hasNetwork(getActivity())){
                            errorText.setText("穿越到火星了，请稍后重试");
                        }else{
                            errorText.setText("当前网络不可用，请检查网络设置");
                        }
                    }
                });
            }
        };
        HDClient.getInstance().addConnectionListener(connectionListener);

    }

    private ArrayList<Fragment> getFragments() {
        ArrayList<Fragment> fragments = new ArrayList<>();
        if (currentSessionFragment == null){
            currentSessionFragment = new CurrentSessionFragment();
            //currentSessionFragment.setMsgFragment(this);
        }

        if (ownerMsgFragment == null){
            ownerMsgFragment = new OwnerMsgFragment();
            ownerMsgFragment.setTitleViewHidden();
        }

//        fragments.add(mWaitAccessFragment);
        fragments.add(currentSessionFragment);
        fragments.add(ownerMsgFragment);

        return fragments;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }


    public void selectTopTab(int position){
        mTabLayout.setCurrentTab(position);
        mViewPager.setCurrentItem(position);
    }

    public CommonTabLayout getmTabLayout(){
        return mTabLayout;
    }


    public void refreshCurUnreadCount() {
        if (currentSessionFragment != null) {
            int curCount = currentSessionFragment.getUnreadCount();

            if (curCount > 0) {
                mTabLayout.showMsg(0, curCount);
                mTabLayout.setMsgMargin(0, 1, 10);
                RoundTextView rtv_agent = mTabLayout.getMsgView(0);
                if (rtv_agent != null) {
                    rtv_agent.getDelegate().setBackgroundColor(Color.rgb(234, 84, 4));
                }
            } else {
                mTabLayout.hideMsg(0);
            }
        }
    }

    public void clearFilter(){
        if(addrSearchView != null){
            addrSearchView.clearViewData();
        }


        filterText.setTextColor(Color.parseColor("#ffffff"));
        searchIcon.setImageResource(R.drawable.hk_select_icon);
    }

    @Override
    public void addrSearchRes(String search, String city, String curCityPinyin, String village, String building, String unit, String edit_str) {
        currentSessionFragment.query.getText().clear();

        currentSessionFragment.getAdapter().getFilter().filter(search);
        // 如果是清空的话
        if(search.equals("")){
            filterText.setTextColor(Color.parseColor("#ffffff"));
            searchIcon.setImageResource(R.drawable.hk_select_icon);
        }else{
            filterText.setTextColor(Color.parseColor("#FFF16D"));
            searchIcon.setImageResource(R.drawable.hk_select_icon_data);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (connectionListener != null){
            HDClient.getInstance().removeConnectionListener(connectionListener);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (connectionListener != null){
            HDClient.getInstance().removeConnectionListener(connectionListener);
        }

    }

    private class MyPagerAdapter extends FragmentPagerAdapter {
        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

    }
}
